package com.ruoyi.system.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.config.AliPay;
import com.ruoyi.system.config.AliPayController;
import com.ruoyi.system.service.IDsStoragemanagementService;
import com.ruoyi.system.util.AmountCalculation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.security.SecureRandom;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.util.*;
import java.util.concurrent.TimeUnit;

import com.ruoyi.system.domain.DsStoragemanagement;

@RestController
@RequestMapping("/VehicleInfo")
public class SxTController extends BaseController {
    @Autowired
    private IDsStoragemanagementService dsStoragemanagementService;
    @Autowired
    AliPayController aliPayController;
    @Autowired
    private RedisTemplate<String, String> redisTemplate;


    @RequestMapping("/getCarNo")
    public AjaxResult getCarNo(HttpServletRequest request) {
        StringBuffer jb = new StringBuffer();
        char[] lineChars = new char[1024 * 1024];
        char[] totalChars = new char[1024 * 1024];
        int readLen = 0;
        int totalLen = 0;
        try {
            BufferedReader reader = request.getReader();
            while ((readLen = reader.read(lineChars)) > 0) {
                for (int i = 0; i < readLen; i++) {
                    totalChars[totalLen + i] = lineChars[i];
                }
                totalLen += readLen;
            }
        } catch (Exception e) {
//            e.printStackTrace(); /*report an error*/
            redisTemplate.opsForHash().put("vehicle", "id", "0");
            return AjaxResult.success("0", "0");
        }

        String lineStr = new String(totalChars);
        System.out.println(lineStr);
        try {
            if (StringUtils.isEmpty(lineStr)) {
                redisTemplate.opsForHash().put("vehicle", "id", "0");
                return AjaxResult.success("0", "0");
            }
            JSONObject jsonObject = JSON.parseObject(lineStr);
            if (jsonObject == null || jsonObject.equals("")) {
                redisTemplate.opsForHash().put("vehicle", "id", "0");
                return AjaxResult.success("0", "0");
            } else {

                // 解析JSON数据,获取车牌号
                String license = jsonObject
                        .getJSONObject("AlarmInfoPlate")
                        .getJSONObject("result")
                        .getJSONObject("PlateResult")
                        .getString("license");
                if (license == null) {
                    redisTemplate.opsForHash().put("vehicle", "id", "0");
                    return AjaxResult.success("0", "0");
                }
                // 将车牌号打印出来
                System.out.println("车牌号: " + license);

                // 查询车辆是否已入库
                long pduanid = dsStoragemanagementService.getselectIDSoto(license);
                if (pduanid == 0) {
                    if (redisTemplate != null) {
                        // 将车牌号、出库时间和金额存入Redis
                        redisTemplate.opsForHash().put("vehicle_info", "license_plate", license);

                        redisTemplate.expire("vehicle_info", 7, TimeUnit.DAYS); // 设置7天过期

                    }
                    long vehicleId;
                    int mation = getVehicleinformation(license); // 查看是否为会员用户
                    int erinfo = getVehicleownerinfo(license); // 查看是否为固定业主
                    if (mation != 0) {
                        vehicleId = getCharacters(mation, 1);
                        redisTemplate.opsForHash().put("vehicle_info", "vehicleId", "会员车辆");
                    } else if (erinfo != 0) {
                        vehicleId = getCharacters(erinfo, 2);
                        redisTemplate.opsForHash().put("vehicle_info", "vehicleId", "固定车辆");
                    } else {
                        vehicleId = getLingShi(0, 0); // 添加为临时用户
                        redisTemplate.opsForHash().put("vehicle_info", "vehicleId", "临时车辆");
                    }
                    DsStoragemanagement ds = new DsStoragemanagement();
                    ds.setVehicleId(vehicleId); // 角色id
                    ds.setLicenseplate(license); // 车牌号
                    int result = dsStoragemanagementService.insertDsStoragemanagement(ds);


                    redisTemplate.opsForHash().put("vehicle", "id", "1");
                    return toAjax(result);
                } else {
                    DsStoragemanagement dsime = new DsStoragemanagement();
                    dsime.setStorageId(pduanid);
                    dsime = dsStoragemanagementService.selectDsStoragemanagementByStorageId(dsime);
                    LocalDateTime now = LocalDateTime.now();
                    ZoneId zoneId = ZoneId.systemDefault();
                    ZonedDateTime zdt = now.atZone(zoneId);
                    Date deliveryDateTime = Date.from(zdt.toInstant());
                    dsime.setDeliveryDateTime(deliveryDateTime); // 出库时间
                    long jiner = AmountCalculation.jiner(dsime.getStorageDateTime(), deliveryDateTime); // 计算金额
                    String randomString = generateRandomString(21);
                    dsime.setOrdernumber(randomString); // 订单号
                    dsime.setAmount(jiner);
                    long i = 1;
                    dsime.setOperationType(i);
//                    int ida = dsStoragemanagementService.updateDsStoragemanagement(dsime);
String inr= String.valueOf(jiner);;
                    if (redisTemplate != null) {
                        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
                        // 将车牌号、出库时间和金额存入Redis
                        redisTemplate.opsForHash().put("vehicle_info", "license_plate", license);
                        redisTemplate.opsForHash().put("vehicle_info", "Ordernumber", dsime.getOrdernumber());
                        redisTemplate.opsForHash().put("vehicle_info", "amount", inr);
                        redisTemplate.opsForHash().put("vehicle_info", "deliveryDateTime", sdf.format(deliveryDateTime));
                        redisTemplate.opsForHash().put("vehicle_info", "pduanid", String.valueOf(pduanid));
                        redisTemplate.expire("vehicle_info", 7, TimeUnit.DAYS); // 设置7天过期
                    }

                    redisTemplate.opsForHash().put("vehicle", "id", "2");
                    return toAjax(2);
                }
            }
        } catch (Exception e) {
//            e.printStackTrace();
            return toAjax(0);
        }
    }

    public int getVehicleinformation(String vehicleInfo) {
        return dsStoragemanagementService.getVehicleinformation(vehicleInfo);
    }

    public int getVehicleownerinfo(String vehicleInfo) {
        return dsStoragemanagementService.getVehicleownerinfo(vehicleInfo);
    }

    public int getCharacters(int id, int mid) {
        return dsStoragemanagementService.getCharacters(id, mid);
    }

    public int getLingShi(int id, int biao) {
        return dsStoragemanagementService.getLingShi(id, biao);
    }

    public static String generateRandomString(int length) {
        String charPool = "0123456789";
        StringBuilder sb = new StringBuilder();
        SecureRandom random = new SecureRandom();
        for (int i = 0; i < length; i++) {
            int index = random.nextInt(charPool.length());
            sb.append(charPool.charAt(index));
        }
        return sb.toString();
    }

    //            WriteTxt("d:\\plate_num.txt", license);
    //把json字符串以txt文件的形式保存
    protected void WriteTxt(String path, String txt) {
        try {
            FileWriter f = new FileWriter(path);
            BufferedWriter bw = new BufferedWriter(f);
            bw.write(txt);
            bw.close();
        } catch (Exception e) {
        }
    }

    @RequestMapping("/panduan")
    public AjaxResult getpduan() {
        Map map = new HashMap<>();
        map.put("license", (String) redisTemplate.opsForHash().get("vehicle", "id"));
        System.out.println("判断结果" + (String) redisTemplate.opsForHash().get("vehicle", "id"));
        return success(map);
    }

    @RequestMapping("/luku")
    public AjaxResult getluku() {
        List<AliPay> list = new ArrayList();

        AliPay aliPay = new AliPay();
        aliPay.setLicense_plate((String) redisTemplate.opsForHash().get("vehicle_info", "license_plate"));
        aliPay.setVehicleId((String) redisTemplate.opsForHash().get("vehicle_info", "vehicleId"));
        aliPay.setId((String) redisTemplate.opsForHash().get("vehicle", "id"));

//        aliPay.setQuery(query);
//        System.out.println("测试"+query);
        list.add(aliPay);
        System.out.println("判断结果" + (String) redisTemplate.opsForHash().get("vehicle_info", "vehicleId"));
        System.out.println("判断结果" + (String) redisTemplate.opsForHash().get("vehicle_info", "license_plate"));
//        if (query.equals("20")) {
//            qingchu();
//        }
        return success(list);
    }


    @RequestMapping("/qingchu")
    public AjaxResult qingchu() {
        if (redisTemplate != null) {
            redisTemplate.opsForHash().put("vehicle", "id", "0");
        }
        return AjaxResult.success("0", "0");
    }
  @RequestMapping("/chuku")
    public AjaxResult chuku() throws ParseException {
      List<AliPay> list = new ArrayList();
      AliPay aliPay = new AliPay();
      if (redisTemplate != null) {
          aliPay.setVehicleInfo((String) redisTemplate.opsForHash().get("vehicle_info", "license_plate"));
        String aine=(String)redisTemplate.opsForHash().get("vehicle_info", "amount");
          aliPay.setAmount(Long.valueOf(aine));
          aliPay.setRnumber((String) redisTemplate.opsForHash().get("vehicle_info", "Ordernumber"));
//          aliPay.setVehicleInfo((String)redisTemplate.opsForHash().get("vehicle_info", "license_plate"));
          SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
          aliPay.setDeliveryDateTime(sdf.parse((String) redisTemplate.opsForHash().get("vehicle_info", "deliveryDateTime")));
          String mind=(String)redisTemplate.opsForHash().get("vehicle_info", "pduanid");
          aliPay.setPduanid(Long.valueOf(mind));
      }

      list.add(aliPay);
        return success(list);
    }

}



